package com.zaizai.controller;

import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.GifCaptcha;
import com.zaizai.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.awt.*;
import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 图片验证码
 */
@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 得到验证码
     */
    @GetMapping("/getCaptcha")
    public AjaxResult getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException, FontFormatException {
        Map<String, Object> map = new HashMap<>();


        // 创建ArithmeticCaptcha对象，设置宽度为160，高度为40，长度为5
        ArithmeticCaptcha arithmeticCaptcha = new ArithmeticCaptcha(160, 40, 2);
        // 获取生成的验证码内容
        final String captcha = arithmeticCaptcha.text().toLowerCase();

        /*// 创建GifCaptcha对象，设置宽度为160，高度为40，长度为5
        GifCaptcha gifCaptcha = new GifCaptcha(160, 40, 5);
        //验证码字符类型
        gifCaptcha.setCharType(GifCaptcha.TYPE_ONLY_NUMBER);
        // 设置内置字体
        gifCaptcha.setFont(GifCaptcha.FONT_3);

        // 获取生成的验证码内容
        final String captcha = gifCaptcha.text().toLowerCase();*/


        // 生成一个随机key
        String key = UUID.randomUUID().toString();
        // 放入到redis中，同时设计过期时间为1分钟
        redisTemplate.opsForValue().set("captcha:" + key, captcha, Duration.ofMinutes(1));
        // 获取生成验证码的base64字符串
        String base64 = arithmeticCaptcha.toBase64();

        map.put("captchaKey", key);
        map.put("captchaBase64", base64);
        return AjaxResult.success(map);
    }
}
